<template>
  <!-- 合同信息 -->
  <div>
    <div class="middle-box">
      <span class="title"> 业务信息 </span>
    </div>
    <div class="btn_asset">
      <span class="btn_left">
        <el-button type="primary" @click="pushNewData"> 新增 </el-button>
        <el-button type="primary" @click="pushNewData"> 中止 </el-button>
        <el-button @click="batchDelete"> 删除 </el-button>
      </span>
      <span class="btn_right">
        <el-button size="small">
          <el-icon style="margin-right: 2px; margin-bottom: 2px"
            ><RefreshRight /></el-icon
          >刷新
        </el-button>
      </span>
    </div>
    <el-table
      max-height="450"
      stripe
      border
      size="small"
      :data="state.tableData.data"
      :cell-class-name="tableCellClassName"
      v-loading="state.tableData.loading"
      @cell-click="cellClick"
      @selection-change="handleSelectionChange"
    >
      <el-table-column align="center" type="selection" width="50" />
      <el-table-column align="center" label="合同编号">
        <template #default="scope">
          <div v-if="scope.row.index === state.rowIndex">
            <selectDown
              v-model:modelData="scope.row.contractNo"
              placeholder="请输入后搜索"
              urlType="currency"
            >
            </selectDown>
          </div>
          <span v-else>
            {{ scope.row.contractNo }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同类型">
        <template #default="scope">
          <div v-if="scope.row.index === state.rowIndex">
            <el-input v-model="scope.row.contractType" size="small"> </el-input>
          </div>
          <span v-else>
            {{ scope.row.contractType }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="合同期限">
        <template #default="scope">
          <div v-if="scope.row.index === state.rowIndex">
            <el-input v-model="scope.row.contractTerm" size="small"> </el-input>
          </div>
          <span v-else>
            {{ scope.row.contractTerm }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="到期提醒">
        <template #default="scope">
          <div v-if="scope.row.index === state.rowIndex">
            <el-input v-model="scope.row.expirationReminder" size="small">
            </el-input>
          </div>
          <span v-else>
            {{ scope.row.expirationReminder }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="中止时间">
        <template #default="scope">
          <div v-if="scope.row.index === state.rowIndex">
            <el-input v-model="scope.row.stopTime" size="small"> </el-input>
          </div>
          <span v-else>
            {{ scope.row.stopTime }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="执行状态">
        <template #default="scope">
          <div v-if="scope.row.index === state.rowIndex">
            <el-input v-model="scope.row.excuteState" size="small"></el-input>
          </div>
          <span v-else>
            {{ scope.row.excuteState }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 创建合同信息 -->
    <el-dialog
      title="银行信息"
      v-model="dialogData.create_contract_show"
      width="448px"
    >
      <el-form
        :model="formData"
        :rules="formRules"
        label-width="60px"
        ref="form"
      >
        <el-row>
          <el-col>
            <el-form-item label="账户类别">
              <el-select
                v-model="value"
                placeholder="请输入"
                size="small"
                fit-input-width
              >
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="账户名称">
              <el-input v-model="input" fit-input-width placeholder="请输入" />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="银行名称">
              <el-input
                v-model="input2"
                style="max-width: 600px"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="银行账户">
              <el-input
                v-model="input2"
                style="max-width: 600px"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
          <el-col>
            <el-form-item label="使用状态">
              <el-input
                v-model="input2"
                style="max-width: 600px"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancel" type="default" size="middle"
            >取消</el-button
          >
          <el-button
            type="primary"
            size="middle"
            style="background: #5d9df5"
            @click="next"
            >保存</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {
  ref,
  reactive,
  onMounted,
  defineProps,
  defineEmits,
  computed,
  toRaw,
} from "vue";
import selectDown from "./selectDown.vue";
import { ElMessageBox, ElMessage } from "element-plus";
import request from "@/public/request";
import { useRoute, useRouter } from "vue-router";

const Route = useRoute();
const Router = useRouter();

const props = defineProps({
  show: {
    type: Boolean,
    default: false,
  },
});
const emit = defineEmits(["update:show"]);

const inShow = computed({
  get() {
    return this.show;
  },
  set(value) {
    this.$emit("update:show", value);
  },
});
const state = reactive({
  rowIndex: -1, //行索引
  columnIndex: -1, //列索引

  btnLoading: false,
  // 表格数据
  tableData: {
    data: [
      {
        id: 1,
        // 合同编号
        contractNo: "111333",
        // 合同类型
        contractType: "收款",
        // 合同期限
        contractTerm: "",
        // 到期提醒
        expirationReminder: 5,
        // 中止时间
        stopTime: "2024-8-31",
        // 执行状态
        excuteState: "启用",
      },
      {
        id: 2,
        // 合同编号
        contractNo: "222333",
        // 合同类型
        contractType: "付款",
        // 合同期限
        contractTerm: "",
        // 到期提醒
        expirationReminder: 5,
        // 中止时间
        stopTime: "2024-8-31",
        // 执行状态
        excuteState: "启用",
      },
    ],
    loading: false,
  },
  copyData: [],

  selectData: [],
  // 将表格选中的数据放入数组中
  tableSelect: [],
  dialogData: {
    create_contract_show: false
  }
})

const handleSelectionChange = (val) => {
  let arr = [];
  for (let item of val) {
    let ret = toRaw(item);
    if (ret !== undefined) {
      arr.push(ret);
    }
  }
  state.tableSelect = arr;
};
// 批量删除点击事件
const batchDelete = () => {
  if (state.tableSelect.length > 0) {
    for (let i = state.tableSelect.length - 1; i >= 0; i--) {
      let deleteIndex = state.tableData.data.findIndex(
        (t) => t == state.tableSelect[i]
      );
      console.log("deleteIndex", deleteIndex);
      if (deleteIndex > -1) {
        state.tableData.data.splice(deleteIndex, 1);
      }
    }
  } else {
    this.$message.error("请先选择");
  }
};

const handleClose = (done) => {
  done();
};
const tableCellClassName = ({ row, column, rowIndex, columnIndex }) => {
  column.index = columnIndex;
  row.index = rowIndex;
};
const cellClick = (row, column, cell, event) => {
  state.rowIndex = row.index;
  state.columnIndex = column.index;
};
// const handleSelectionChange = (selection) => {
//   state.selectData = selection;
// };
// const initData = () => {
//   if (!Route.query.entId) {
//     return;
//   }
//   state.tableData.loading = true;
//   request
//     .get("/api/buenterprisebank/query", {
//       EntId: Route.query.entId,
//     })
//     .then((res) => {
//       state.tableData.data = res;
//       state.copyData = res;
//     })
//     .finally(() => (state.tableData.loading = false));
// };
const pushNewData = () => {
  state.tableData.data.push({
    entId: Route.query.entId,
    currency: "",
    accountName: "",
    bankAccount: "",
    bankName: "",
    memo: "",
  });
};
// const deleteData = () => {
//   let newArray = [];
//   state.tableData.data.forEach((t) => {
//     if (!state.selectData.find((item) => t == item)) {
//       newArray.push(t);
//     }
//   });
//   state.tableData.data = newArray;
// };
const validData = () => {
  for (let i of state.tableData.data) {
    for (let j of Object.keys(i)) {
      if (
        j == "currency" ||
        j == "accountName" ||
        j == "bankAccount" ||
        j == "bankName" ||
        j == "entId"
      ) {
        if (!i[j]) {
          return false;
        }
      } else {
        continue;
      }
    }
  }
  return true;
};
const save = () => {
  if (state.tableData.data.length == 0) {
    ElMessage.warning("表格中没有数据");
    return;
  }
  if (validData()) {
    let newFormData = JSON.parse(JSON.stringify(state.tableData.data));
    newFormData.forEach((t) => {
      delete t.index;
    });
    // 判断列表数据是否存在币种，收款户名，银行账号，开户账户是否有完全相同的数据
    let hasSameObj = false;
    for (let i = 0; i < newFormData.length; i++) {
      hasSameObj = false;
      let checkObj = newFormData[i];
      for (let j = i + 1; j < newFormData.length; j++) {
        let sigleObj = newFormData[j];
        if (
          checkObj.currency == sigleObj.currency &&
          checkObj.accountName == sigleObj.accountName &&
          checkObj.bankAccount == sigleObj.bankAccount &&
          checkObj.bankName == sigleObj.bankName
        ) {
          hasSameObj = true;
          break;
        }
      }
      if (hasSameObj) {
        break;
      }
    }
    if (hasSameObj) {
      ElMessage.warning("列表数据存在两条相同的数据");
      return;
    }
    this.btnLoading = true;
    request
      .post("/api/buenterprisebank/save", {
        entId: Route.query.entId,
        bankList: newFormData,
      })
      .then((res) => {
        if (res.status) {
          ElMessage.success(res.message);
        } else {
          ElMessage.error(res.message);
        }
      })
      .finally(() => (state.btnLoading = false));
  } else {
    ElMessage.warning("数据中存在币种、收款户名、银行账号、开户账号为空");
  }
};
onMounted(() => {
  // initData();
});
</script>

<style lang="scss" scoped>
.middle-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  .title {
    border-left: 2px solid #5d9df5;
    padding-left: 4px;
    font-size: 16px;
    font-weight: 600;
  }
}
.btn_asset {
  margin: 8px 0;
  display: flex;
  justify-content: space-between;
}
</style>
